from flask import Blueprint, request, jsonify, session
from models.User import User
from models.Company import Company
from models import db

company_bp = Blueprint('company', __name__)


@company_bp.route('/companies')
def get_company_info():
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'success': False, 'message': '未登录'}), 401

    user = User.query.get(user_id)
    company = Company.query.filter_by(user_id=user_id).first()

    if not user or not company:
        return jsonify({'success': False, 'message': '企业不存在'}), 404

    return jsonify({
        'success': True,
        'company': {
            'company_name': company.company_name,
            'industry': company.industry,
            'address': company.address,
            'scale': company.scale,
            'website': company.website,
            'contact_phone': company.contact_phone,
        }
    })


@company_bp.route('/companies/update', methods=['POST'])
def update_company_info():
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'success': False, 'message': '未登录'}), 401

    data = request.get_json()
    user = User.query.get(user_id)
    company = Company.query.filter_by(user_id=user_id).first()

    if not user or not company:
        return jsonify({'success': False, 'message': '企业不存在'}), 404

    company.company_name = data.get('company_name', company.company_name)
    company.industry = data.get('industry', company.industry)
    company.address = data.get('address', company.address)
    company.scale = data.get('scale', company.scale)
    company.website = data.get('website', company.website)
    company.contact_phone = data.get('contact_phone', company.contact_phone)
    if data.get('password'):
        user.password = data['password']  # 更新密码

    db.session.commit()

    return jsonify({
        'success': True,
        'company': {
            'company_name': company.company_name,
            'industry': company.industry,
            'address': company.address,
            'scale': company.scale,
            'website': company.website,
            'contact_phone': company.contact_phone,
        }
    })
